package Demo2;

import java.util.Arrays;

public class SqlList {
    private int[] elem = new int[DEFAULT_CAPACITY];
    private int useSize;
    private static final int DEFAULT_CAPACITY = 5;


    // 打印顺序表，注意：该方法并不是顺序表中的方法，为了方便看测试结果给出的
    public void display(){
        for (int i = 0; i < this.useSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    // 新增元素,默认在数据最后新增
    public void add(int data){
        if (isFull()){
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }else{
            elem[useSize] = data;
            useSize++;
        }
    }
    public boolean isFull(){
        if (this.useSize == elem.length){
            return true;
        }else{
            return false;
        }
    }


    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    // 查找某个元素对应的下标
    public int indexOf(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    // 获取 pos 位置的元素
    public int get(int pos) {
        if (!checkPos(pos)){
            //throw new PosException("pos不在合法范围中");
        }
        return this.elem[pos];
    }

    private boolean checkPos(int pos){
        if (pos <= useSize && pos > 0){
            return true;
        }else{
            return false;
        }
    }

    // 获取顺序表长度
    public int size() {
        return useSize;
    }

    // 给 pos 位置的元素设为 value
    public void set(int pos, int value) {
        if (!checkPos(pos)){
           // throw new PosException("pos不在合法范围中");
        }
        elem[pos] = value;
    }

    // 给 pos 位置的元素设为 value
    public void add(int pos, int value) {
        if (pos < 0 || pos > useSize){
          //  throw new PosException("add 中下标的位置不对");
        }

        if(isFull()) {
            elem = Arrays.copyOf(elem,2*elem.length);
        }

        for (int i = useSize; i > pos ; i--) {
            elem[i + 1] = elem[i];
        }

        this.elem[pos] = value;
        this.useSize++;

    }


    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        if (isEmpty()){
            return;
        }

        int index = indexOf(toRemove);
        if(index == -1) {
            return;//没有你要删除的数字
        }

        for (int i = index; i < useSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }

        this.useSize--;
        //elem[us] = null;     如果是引用类型，需要手动置空
    }
    public boolean isEmpty() {
        return useSize == 0;
    }
    // 清空顺序表
    public void clear() {
        //这是引用类型的做法
        /*for (int i = 0; i < useSize; i++) {
            this.elem[i] = null;
        }*/

        useSize = 0;
    }

}
